<template>
  <div class="userinfo-container">
    <el-card class="userinfo-card">
      <div slot="header" class="card-header">
        <span>个人信息</span>
        <el-button type="primary" size="small" @click="editUserInfo" v-if="!isEditing">编辑</el-button>
        <div v-else>
          <el-button type="success" size="small" @click="saveUserInfo">保存</el-button>
          <el-button size="small" @click="cancelEdit">取消</el-button>
        </div>
      </div>
      
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px" :disabled="!isEditing">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="password-card">
      <div slot="header" class="card-header">
        <span>修改密码</span>
      </div>
      
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="passwordLoading">修改密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserInfo',
  data() {
    // 自定义验证规则 - 确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    // 自定义验证规则 - 手机号
    const validatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    // 自定义验证规则 - 邮箱
    const validateEmail = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }
    return {
      // 是否正在编辑个人信息
      isEditing: false,
      // 个人信息表单
      userForm: {
        id: this.$store.state.userInfo.id,
        username: '',
        name: '',
        phone: '',
        email: ''
      },
      // 个人信息表单验证规则
      userRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      // 修改密码表单
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 修改密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 修改密码按钮加载状态
      passwordLoading: false,
      // 保存用户信息前的备份
      userInfoBackup: {}
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    // 初始化用户信息
    this.initUserInfo()
  },
  methods: {
    // 初始化用户信息
    initUserInfo() {
      this.userForm = {
        id: this.$store.state.userInfo.id,
        username: this.userInfo.username || '',
        name: this.userInfo.name || '',
        phone: this.userInfo.phone || '',
        email: this.userInfo.email || ''
      }
    },
    // 编辑用户信息
    editUserInfo() {
      // 备份当前用户信息，用于取消编辑时恢复
      this.userInfoBackup = JSON.parse(JSON.stringify(this.userForm))
      this.isEditing = true
    },
    // 保存用户信息
    saveUserInfo() {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return
        try {
          // 发送更新用户信息请求
          const { data: res } = await this.$http.put('/user/info', this.userForm)
          if (res.code !== 200) {
            return this.$message.error(res.message || '更新个人信息失败')
          }
          // 更新成功
          this.$message.success('个人信息更新成功')
          // 更新Vuex中的用户信息
          this.$store.commit('SET_USER_INFO', {
            ...this.userInfo,
            ...this.userForm
          })
          this.isEditing = false
        } catch (error) {
          console.error('更新个人信息失败', error)
          this.$message.error('更新个人信息失败，请稍后重试')
        }
      })
    },
    // 取消编辑
    cancelEdit() {
      // 恢复备份的用户信息
      this.userForm = JSON.parse(JSON.stringify(this.userInfoBackup))
      this.isEditing = false
      // 重置表单验证
      this.$refs.userFormRef.clearValidate()
    },
    // 修改密码
    changePassword() {
      this.$refs.passwordFormRef.validate(async valid => {
        if (!valid) return
        this.passwordLoading = true
        try {
          // 发送修改密码请求
          const { data: res } = await this.$http.put('/user/password', {
            id: this.$store.state.userInfo.id,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          })
          if (res.code !== 200) {
            return this.$message.error(res.message || '修改密码失败')
          }
          // 修改成功
          this.$message.success('密码修改成功，请重新登录')
          // 清除登录信息，跳转到登录页
          this.$store.dispatch('logout')
          this.$router.push('/login')
        } catch (error) {
          console.error('修改密码失败', error)
          this.$message.error('修改密码失败，请稍后重试')
        } finally {
          this.passwordLoading = false
        }
      })
    },
    // 重置密码表单
    resetPasswordForm() {
      this.$refs.passwordFormRef.resetFields()
    }
  }
}
</script>

<style scoped>
.userinfo-container {
  padding: 20px;
}

.userinfo-card, .password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form {
  max-width: 500px;
  margin: 0 auto;
}
</style>